package com.orangelife.mobile.main.fragment;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.jump.PayJumper;
import com.common.jump.PropertyJumper;
import com.common.jump.WebJumper;
import com.common.sp.CommSp2;
import com.common.sp.PaySp;
import com.common.sp.UserSp;
import com.common.util.CommonHttpBiz;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.MoneyUtil;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.android.view.BadgeView;
import com.curry.orangelife.mobile.R;
import com.common.jump.JumpManager;
import com.common.jump.MessageJumper;
import com.datatrack.DataTrack;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.WebViewURL;
import com.orangelife.mobile.houserepair.activity.MyRepairListActivity;
import com.orangelife.mobile.individual.activity.IndividualInformationActivity;
import com.orangelife.mobile.goodsOrder.activity.MyGoodsOrderListActivity;
import com.orangelife.mobile.individual.biz.PersonalBiz;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.main.biz.MainHttpBz;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.biz.PayHttpBiz;
import com.orangelife.mobile.pay.biz.PayPwdHttpBiz;
import com.orangelife.mobile.pay.view.PayPwdDialog;
import com.orangelife.mobile.point.activity.MyPointActivity;
import com.orangelife.mobile.individual.activity.MyWalletActivity;
import com.orangelife.mobile.individual.activity.SettingActivity;
import com.orangelife.mobile.main.activity.ServiceOrderActivity;
import com.orangelife.mobile.myhouse.biz.HouseBiz;
import com.orangelife.mobile.voucher.activity.MyVoucherListActivity;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.widget.RoundImageViewByXfermode;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的
 *
 * @author cx
 */
public class Page4Fragment extends OrangeLifeBaseFragment {

    private View homePageView;

    /** 头像 */
    @Bind(R.id.ivHeadPortrait)
    RoundImageViewByXfermode ivHeadPortrait;
    @Bind(R.id.tvName)
    TextView tvName;
    /** 钱包余额 */
    @Bind(R.id.tv_wallet_balance)
    TextView tvWalletBalance;
    /** 抵用 */
    @Bind(R.id.tv_voucher)
    TextView tvVoucher;
    /** 橙汁积分 */
    @Bind(R.id.tv_orange_juice)
    TextView tvOrangeJuice;
    /** 认证 */
    @Bind(R.id.tvValidityTip)
    TextView tvValidityTip;
    /** 消息按钮 */
    @Bind(R.id.ib_message)
    ImageView ibMessage;
    @Bind(R.id.tv_service_phone)
    TextView tvServicePhone;
    /** 社区活动订单数量 */
    @Bind(R.id.tvCommActOrderNum)
    TextView tvCommActOrderNum;
    //    @Bind(R.id.ivPropertyOrder)
//    ImageView ivPropertyOrder;
//    @Bind(R.id.ivServiceOrder)
//    ImageView ivServiceOrder;
//    @Bind(R.id.ivGoodOrder)
//    ImageView ivGoodOrder;
    @Bind(R.id.tvPropertyWalletPrice)
    TextView tvPropertyWalletPrice;
    @Bind(R.id.tvPropertyWalletRechargeReturn)
    TextView tvPropertyWalletRechargeReturn;

    /** 未读消息数量角标 */
    private BadgeView bvMsgNum;
//    private BadgeView bvPropertyOrderNum;
//    private BadgeView bvServiceOrderNum;
//    private BadgeView bvGoodOrderNum;

    /** 是否被销毁 */
    private boolean isDestroyView;

    /** Activit 名称 **/
    final String MODULE_NAME = "/mine";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        isDestroyView = false;
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.fragment_mine2,
                    container, false);
            ButterKnife.bind(this, homePageView);
            initBadgeView();
        } else {
            ButterKnife.bind(this, homePageView);
        }
        isConnected();
        clearChildView(homePageView);
        initServicePhone();
        return homePageView;
    }

    /**
     * 数据采集体不要删除
     *
     * @return
     */
    public Map<String, Object> getDataTrack() {
        Map<String, Object> map = new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    @Override
    public void onResume() {
        super.onResume();
        initHeadPhoto();
        requestPersonalInfo();
        requestOtherService();
        requestPropertyWalletMoney();
        requestPayPwdInfo();
    }

    private void initBadgeView() {
        bvMsgNum = new BadgeView(getActivity());
        bvMsgNum.setTargetView(ibMessage);
        bvMsgNum.setBadgeGravity(Gravity.RIGHT | Gravity.TOP);
        bvMsgNum.setBackgroundResource(R.drawable.shape_red_point);
        bvMsgNum.setTextSize(9);
        bvMsgNum.setBadgeMargin(10, 1, 0, 0);
        bvMsgNum.setGravity(Gravity.CENTER);
    }

    private void initServicePhone() {
        tvServicePhone.setText("服务热线：" + CommSp2.getCustomerServicePhone());
    }

    /** 我的界面 获取用户是否认证以及消息提醒的条数 */
    private void requestPersonalInfo() {
        PersonalBiz.getPersonalInfo(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (isDestroyView) {
                    return;
                }
                int msgCount = PersonalBiz.handlePersonalInfo(jsonObject);
                tvValidityTip.setText(HouseBiz.getCertInfo());
                if (msgCount == 0) {
                    bvMsgNum.setVisibility(View.GONE);
                } else {
                    bvMsgNum.setBadgeCount(msgCount);
                }
            }
        });
    }


    /** 我的界面 其它服务:我的可用积分(橙汁),我的可用金额,我的可用抵用券 */
    private void requestOtherService() {
        PersonalBiz.getOtherService(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int i) {
                if (isDestroyView) {
                    return;
                }
                Map<String, Object> map = CommonHttpBiz.handleEntityWithoutToast(response);
                if (map != null) {
                    tvWalletBalance.setText(DecimalUtil.decimalFormat(String.valueOf(map.get("money"))));
                    tvOrangeJuice.setText(String.valueOf(map.get("validPoints")) + "ml");
                    tvVoucher.setText(String.valueOf(map.get("coupon")) + "张");
                }
            }
        });
    }

    /** 请求物业费钱包余额信息 */
    private void requestPropertyWalletMoney() {
        PayHttpBiz.getPropertyWalletMoney(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (isDestroyView) {
                    return;
                }
                Map<String, Object> map = CommonHttpBiz.handleEntityWithoutToast(jsonObject);
                if (map != null) {
                    String money = String.valueOf(map.get("money"));
                    String rechargeRules = String.valueOf(map.get("rechargeRules"));
                    tvPropertyWalletPrice.setText(Constant.RMB_FLAG + MoneyUtil.handleMoney(money));
                    tvPropertyWalletRechargeReturn.setText(rechargeRules);
                }
            }
        });
    }

    private void requestMyCommActNumber() {
        MainHttpBz.getMyCommActOrderNum(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
//                    String.valueOf(map.get("payment"));
//                    String.valueOf(map.get("service"));
//                    String.valueOf(map.get("goods"));
                    String actCount = String.valueOf(map.get("actCount"));
                    tvCommActOrderNum.setText(actCount);
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        PersonalBiz.cancelPage4Request();
        ButterKnife.unbind(this);
        isDestroyView = true;
        BLog.getInstance().outAppmod(BLog.MINE);
    }


    /**
     * 取头像图片
     */
    private void initHeadPhoto() {
        String imgUrl = UserSp.getProtraitImg();
        if (!StringUtil.isBlank(imgUrl)) {
            ImageDownloader.getImageDownloader().download(UserSp.getProtraitImg(), ivHeadPortrait,
                    ImageDownloader.ImageSize.IMAGE_SIZE_SMALL_PNG);
        } else {
            ivHeadPortrait.setImageDrawable(getResources().getDrawable(R.drawable.icon_head));
            //			rivHeadImage.setBackgroundResource(R.drawable.icon_head);
        }
        tvName.setText(UserSp.getNickname());
    }


    @OnClick({R.id.rlPropertyWallet, R.id.rlPropertyPay, R.id.rlRecharge, R.id.rlMyCommAct, R.id.ib_setting, R.id.includeMine, R.id.rl_wallet_balance, R.id.rl_orange_juice, R.id.rl_voucher, R.id.llPayOrder, R.id.llShopOrder, R.id.llServiceOrder, R.id.ib_message, R.id.rlItem3, R.id.tv_service_phone})
    public void OnClick(View view) {
        intentActivity(view);
    }

    private void jumpToPropertyWalletRecharge() {
        WebJumper.jumpToPropertyWalletRecharge(getActivity());
    }

    private void jumpToPropertyWalletPay() {
        WebJumper.jumpToPropertyWalletPay(getActivity());
    }

    private void jumpToPropertyWalletDetail() {
        WebJumper.jumpToPropertyWalletDetail(getActivity());
    }

    private void intentActivity(View view) {
        switch (view.getId()) {
            case R.id.rlPropertyWallet:
                jumpToPropertyWalletDetail();
                break;
            case R.id.rlPropertyPay:/*物业缴费钱包支付*/
                checkPayPwd();
                break;
            case R.id.rlRecharge:/*物业缴费钱包充值*/
                jumpToPropertyWalletRecharge();
                break;
            case R.id.ib_setting:/*设置*/
                //跳转配置界面
                IntentHelper.getInstances().getIntent(getActivity(), SettingActivity.class);
                dataTrackClick("btnSetting", null);
                break;
            case R.id.includeMine:/*个人信息 */
                IntentHelper.getInstances().getIntent(getActivity(), IndividualInformationActivity.class);
                dataTrackClick("perCenter", null);
                break;
            case R.id.llPayOrder:/*缴费订单*/
                PropertyJumper.jumpToPropertyHistoryList(getActivity());
                dataTrackClick("btnPropertyOdr", null);
                break;
            case R.id.llServiceOrder:/*服务订单*/
                IntentHelper.getInstances().getIntent(getActivity(), ServiceOrderActivity.class);
                dataTrackClick("btnServOdr", null);
                break;
            case R.id.llShopOrder:/*商品订单*/
                IntentHelper.getInstances().getIntent(getActivity(), MyGoodsOrderListActivity.class);
                dataTrackClick("btnGoodOdr", null);
                break;
            case R.id.ib_message:/*消息*/
                MessageJumper.jumpToMessageList(getActivity());
                dataTrackClick("btnMsg", null);
                break;
            case R.id.rl_wallet_balance:/*钱包余额*/
                IntentHelper.getInstances().getIntent(getActivity(), MyWalletActivity.class);
                dataTrackClick("btnWallet", null);
                break;
            case R.id.rl_orange_juice:/*橙汁积分*/
                IntentHelper.getInstances().getIntent(getActivity(), MyPointActivity.class);
                dataTrackClick("btnOrgJuice", null);
                break;
            case R.id.rl_voucher:/*抵用卷*/
                IntentHelper.getInstances().getIntent(getActivity(), MyVoucherListActivity.class);
                dataTrackClick("btnCoupon", null);
                break;
            case R.id.rlItem3:/*报修投诉合并为报事报修,保留的相关接口为报修*/
                IntentHelper.getInstances().getIntent(getActivity(), MyRepairListActivity.class);
                dataTrackClick("btnRepairRcd", null);
                break;
            case R.id.tv_service_phone:
                OrangePhoneUtil.callCustomerService2(getActivity());
                dataTrackClick("textServPhone", null);
                break;
            case R.id.rlMyCommAct:
                WebJumper.jumpToCommunityActivityOrderList(getActivity());
                dataTrackClick("btnCAOdr", null);
                break;
            default:
                break;
        }
    }

    // TODO: 2017-1-6 抽出
    /*=========支付密码弹出框start========*/

    private String statusCode = "-1";
    private String statusInfo;

    /** 请求支付密码信息 */
    private void requestPayPwdInfo() {
        //刚进入首页的时候,不显示进度条,提升体验度.点击的时候,如果没有请求成功,再请求一次.
        PayPwdHttpBiz.getPayPwdInfo(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                Map<String, Object> map = CommonHttpBiz.handleEntity(jsonObject, false);
                if (map != null) {
                    statusCode = String.valueOf(map.get("stateCode"));
                    statusInfo = String.valueOf(map.get("stateInfo"));
                    //useCount
                    //freezeTime
                }
            }
        });
    }

    /** 是否需要输入支付密码 */
    private void checkPayPwd() {
        if ("0".equals(statusCode)) {//已设置
            showPayPwd();
            PaySp.setNeverSetPayPwd(true);
        } else if ("2".equals(statusCode)) {//被冻结
            showFrozenDialog();
            PaySp.setNeverSetPayPwd(true);
        } else if ("1".equals(statusCode)) {
            jumpToPropertyWalletPay();
        } else {
            ToastHelper.getInstance()._toast("获取支付密码状态失败,请稍后再试");
            requestPayPwdInfo();
        }
    }

    /** 支付密码弹出框 */
    private void showPayPwd() {
        final PayPwdDialog ppd = new PayPwdDialog(getActivity(), false);
        ppd.setOnValidatePayPwdListener(new PayPwdDialog.OnValidatePayPwdListener() {
            @Override
            public void onValidated(String statusCode2, String statusInfo2) {
                if ("0".equals(statusCode)) {//成功
                    ppd.dismiss();//执行原先的流程
                    jumpToPropertyWalletPay();
                } else if ("2".equals(statusCode)) {//冻结
                    ppd.dismiss();//关闭密码框
                    statusCode = statusCode2;
                    statusInfo = statusInfo2;
                    showFrozenDialog();//显示冻结框
                } else {//失败,设置标题
                    ppd.clearInput();
                    ppd.setTitle(statusInfo2);
                }
            }
        });
        ppd.show();
        ppd.showKeyboard();
    }

    private void showFrozenDialog() {
        /** 弹出对话框 */
        final ConfirmDialog confirmDialog = new ConfirmDialog(getActivity(), "请找回支付密码", statusInfo, "取消", "找回密码");
        confirmDialog.setCanceledOnTouchOutside(false);
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                confirmDialog.dismiss();
            }

            @Override
            public void doRight() {
                jumpToModPayPwd();
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }

    private void jumpToModPayPwd() {
        PayJumper.jumpToModPwd(getActivity(), true);
    }

    /*=========支付密码弹出框end========*/

}
